const { Sales } = require("../models/salesModel");
const { moveFiles, removeFiles } = require("../utils/upload.js");
//新增销售员
async function addSales(req, res) {
    const { username, avatarImg, tell, age, gender, clientId = [], orderId = [] } = req.body;

    try {
        await Sales.create({ username, avatarImg, tell, age, gender, clientId, orderId });
        //移动图片 说明：下面代码在组件中使用图片上传时打开去掉注释就可以上传图片，目前只能上传图片名字
        if (avatarImg) {
            moveFiles({
                formPath: './public/temp',
                toPath: './public/images',
                filename: avatarImg
            });
            removeFiles('./public/temp');
        }
        res.send({
            message: "新增销售员成功",
            status: 1
        });
    } catch (error) {
        console.log('新增销售失败', error);
        res.send({
            message: "新增销售员失败",
            status: 0,
        });

    }
}
//销售注册
let jwt = require("jsonwebtoken")
async function register(req, res, next) {
    const { username, password } = req.body
    console.info(username)
    const userAlreadyExists = await Sales.find({ username })
    if (userAlreadyExists.length > 0) {
        res.send({
            message: "User already exists, try use other username",
            status: 0
        })
    } else {
        await Sales.create({ username, password })
        res.send({
            message: "register success",
            status: 1
        })
    }
}
//销售登录
async function login(req, res, next) {
    const { username, password } = req.body
    const data = await Sales.find({ username, password })
    if (data.length > 0) {
        let token = jwt.sign(
            { username },
            "iouhfioahufh",
            { expiresIn: 60 * 100 },
        )
        res.send({
            token,
            message: "login success",
            status: 1,
        })
    } else {
        res.send({
            message: "login failed",
            status: 0
        })
    }
}
//获取所有的销售员
async function getSales(req, res) {
    const { pageSize = 5, currentPage = 1 } = req.query;
    //总条数
    const total = await Sales.countDocuments();
    //总页数
    const totalPages = Math.ceil(total / pageSize);
    try {
        const data = await Sales
            .find()
            .limit(pageSize - 0) //设置请求的条数
            .skip((currentPage - 1) * pageSize) //设置跳过的条数
            .populate('clientsId')
            .populate('ordersId')
        res.send({
            status: 1,
            message: '获取信息成功',
            data: { total, totalPages, data, pageSize, currentPage }
        })
    } catch (error) {
        console.log("获取销售员失败", error);
        res.send({
            status: 0,
            message: '获取信息失败'
        })
    }
}
//通过id删除销售员
async function deteSalesById(req, res) {
    const { _id } = req.body;
    try {
        const data = await Sales.findByIdAndDelete(_id)
        if (data) {
            res.send({
                status: 1,
                message: '删除成功'
            })
        } else {
            res.send({
                status: 0,
                message: '删除失败'
            })
        }
    } catch (error) {
        console.log('删除失败', error);
        res.send({
            status: 0,
            message: '删除失败'
        })
    }

}
//获取需要修改的销售员信息
async function getUpdataOne(req, res) {
    const { _id } = req.query;
    const data = await Sales.find({ _id });
    try {
        // console.log(data);
        res.send({
            status: 1,
            message: "获取成功",
            data,
        });
    } catch (error) {
        console.log(error);
        res.send({
            status: 0,
            message: "获取失败"
        });
    }

}
//修改销售员信息
async function SureupdataOne(req, res) {
    const { _id, username, password, tell, age, gender, } = req.body;
    const data = await Sales.updateOne({ _id }, { username, password, tell, age, gender, });
    try {
        console.log(data);
        if (data.nModified) {
            res.send({
                status: 1,
                message: '修改成功'
            });
        } else {
            res.send({
                status: 0,
                message: '修改失败'
            });
        }
    } catch (error) {
        console.log(error);
    }
}
//获取此销售下的客户信息






module.exports = { addSales, login, register, getSales, deteSalesById, getUpdataOne, SureupdataOne }

